import java.io.*;
import javax.jms.*;

public class SubscribeTopicMessage {

 public static void main(String[] args) {
  try {
		//declare all local variables
		TopicConnectionFactory topicConnectionFactory = null;
		Topic topic = null;
		TopicConnection topicConnection = null;
		TopicSession topicSession = null;
		TopicSubscriber topicSubscriber = null;
		TextListener listener = null;

		//lookup for connectionfactory
		topicConnectionFactory = new 
						com.sun.messaging.TopicConnectionFactory();
		//lookup for the destination queue
		topic = new com.sun.messaging.Topic("sampleTopic");
		//create a connection
		topicConnection = 
					  topicConnectionFactory.createTopicConnection();
		//create a session
		topicSession = topicConnection.createTopicSession(false, 
									 Session.AUTO_ACKNOWLEDGE);
		//create a subscriber
		topicSubscriber = topicSession.createSubscriber(topic);
		//create a listener
		listener = new TextListener();
		//register the listener
		topicSubscriber.setMessageListener(listener);
		topicConnection.start();
		//wait for user input to terminate
		InputStreamReader console = new 
								   InputStreamReader(System.in);
		char ans = (char)console.read();
		if(ans == 'q' || ans == 'Q')
			topicConnection.close();
		}
		catch(JMSException e) {
			System.out.println(e);
		}
		catch(IOException e) {
			System.out.println(e);
		}
	}
}

class TextListener implements MessageListener {

	public void onMessage(Message msg) {
	try{
    	TextMessage message = (TextMessage) msg;
		System.out.println("Message Received : "+
										  message.getText());
		} catch (JMSException j){
			System.out.println("Exception:"+j.toString());
		}
	}
}
